
import ejb.ExCourseFacade;
import entity.ExCourse;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@ManagedBean(name = "ExchangeBean")
@SessionScoped
public class ExchangeBean {

    @EJB
    private ExCourseFacade exCourseFacade;
    private ExCourse exCourse;
    @PersistenceContext(unitName = "WebApplication2PU")
    private EntityManager em;
    private List<ExCourse> exCourses;
    private String sellCurrency;
    private String buyCurrency;
    private List<String> currencies;
    private float coeff;

    public List<ExCourse> retrieve() {
        return exCourseFacade.findAll();
    }

    public String getBuyCurrency() {
        return buyCurrency;
    }

    public void setBuyCurrency(String buyCurrency) {
        this.buyCurrency = buyCurrency;
    }

    public String getSellCurrency() {
        return sellCurrency;
    }

    public void setSellCurrency(String sellCurrency) {
        this.sellCurrency = sellCurrency;
    }

    public List<String> getCurrencies() {
        currencies = new ArrayList();
        List<ExCourse> allCourses = em.createNamedQuery("ExCourse.findAll").getResultList();
        for (ExCourse someExCourse : allCourses) {
            currencies.add(someExCourse.getCurrency());
        }

        return currencies;
    }

    public float getCoefficient() {

        List<ExCourse> fromCurrencyList;
        List<ExCourse> toCurrencyList;

        Query fromCurrencyQuery = em.createNamedQuery("ExCourse.findByCurrency").setParameter("currency", sellCurrency);
        Query toCurrencyQuery = em.createNamedQuery("ExCourse.findByCurrency").setParameter("currency", buyCurrency);

        System.out.println("From currency:" + sellCurrency + ", buy currency:" + buyCurrency);

        fromCurrencyList = fromCurrencyQuery.getResultList();
        toCurrencyList = toCurrencyQuery.getResultList();

        coeff = toCurrencyList.get(0).getIndollars() / fromCurrencyList.get(0).getIndollars();

        return coeff;
    }
}
